package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AuctionSpecialInfo_Adapter;
import artid.com.arttogo.bean.AuctionLotListParser;
import artid.com.arttogo.bean.SpecialInfoParser;
import artid.com.arttogo.bean.UpdataSystemMessageParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.utils.VeDate;
import artid.com.arttogo.view.CircleImageView;
import artid.com.arttogo.view.DynamicHeightImageView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 * 项目名称：ArtworkArt 类名称：AuctionSpecialInfo_Activity 类描述：拍卖行-专场详情 创建人：耿卫斌
 * 创建时间：2017-3-1 下午3:44:42
 */
public class AuctionSpecialInfo_Activity extends BaseActivity implements
        OnClickListener, XListView.IXListViewListener {
    private ImageView backBtn,titleCollectionBtn, shareBtn,company_icon;
    private DynamicHeightImageView specialImg;
    private RelativeLayout specialRL;
    private TextView title, time, address, state, company, addRemind, num,
            downloadCatalogue;
    private LinearLayout auctionSpecialInfo_LL,noDataLL;
    private View mHeadView;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private XListView mListView;
    private AuctionSpecialInfo_Adapter mAdapter;
    private String SpecialID;// 专场ID
    private SpecialInfoParser mSpecialInfoParser;
    private String imgwide;// 请求的图片宽度
    private List<AuctionLotListParser.AuctionLotList_Lotinfo> list = new ArrayList<AuctionLotListParser.AuctionLotList_Lotinfo>();
    private List<AuctionLotListParser.AuctionLotList_Lotinfo> more_list = new ArrayList<AuctionLotListParser.AuctionLotList_Lotinfo>();
    private String messageID;//推送消息ID
    private ArrayList<String> listLotIds = new ArrayList<>();//拍品ID集合，主要是实现可以左右滑动
    private TextView titleContent;
    private int dataNum;//数据总条数
    private int requestDataNum=20;//请求数据数量
    private Boolean isLoad=true;//是否加载数据（默认可以加载）
    private String imgwide_SpecialInfo;// 专场图片宽度
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auctionspecialinfo);
        initView();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public int getScrollY() {
        int top = mHeadView.getTop();
        return -top;
    }

    private void initView() {
        mContext = AuctionSpecialInfo_Activity.this;
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
        imgwide_SpecialInfo = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 1) + "";
        // 头布局
        mHeadView = View.inflate(this, R.layout.auctionspecialinfo_head, null);
        titleContent = (TextView) findViewById(R.id.tittle_text);
        backBtn = (ImageView) findViewById(R.id.back_btn);
        backBtn.setOnClickListener(this);
        titleCollectionBtn = (ImageView) findViewById(R.id.AuctionSpecialInfo_title_collectionBtn);
        titleCollectionBtn.setVisibility(View.GONE);
        titleCollectionBtn.setOnClickListener(this);
        shareBtn = (ImageView) findViewById(R.id.tittle_search);
        shareBtn.setImageResource(R.drawable.jg_xq_share);
        shareBtn.setVisibility(View.VISIBLE);
        shareBtn.setOnClickListener(this);
        IntentFilter filter = new IntentFilter("com.AuctionSpecialInfo_Activity.receiver");
        registerReceiver(broadcastReceiver, filter);
        SpecialID = getIntent().getStringExtra("SpecialID");
        if (getIntent().getBooleanExtra("isPush", false)) {
            //判断是否是推送消息进入
            messageID = getIntent().getStringExtra("messageID");
            updataSystmeMessage(messageID);
        }
        auctionSpecialInfo_LL=(LinearLayout)findViewById(R.id.AuctionSpecialInfo_LL);
        auctionSpecialInfo_LL.setVisibility(View.GONE);
        mListView = (XListView) findViewById(R.id.AuctionSpecialInfo_listView);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(this);
        mListView.setVisibility(View.GONE);
        mListView.setOnScrollListener(new PLA_AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                Log.d("log","firstVisibleItem:"+firstVisibleItem+"===visibleItemCount:"+visibleItemCount+"===totalItemCount:"+totalItemCount);

                if(more_list.size()!=dataNum && isLoad==true){
                    //-11是数据已经显示一半的时候如果加头了就-12
                    //-12是数据已经显示一半的时候（因为是瀑布流并且加了头所以-12）
                    if(page==1 && firstVisibleItem==(requestDataNum-12)){
                        page++;
                        getLotListData(false);
                    }else if(((page*requestDataNum)-12)==firstVisibleItem){
                        page++;
                        getLotListData(false);
                    }
                }
            }
        });


        specialRL = (RelativeLayout) mHeadView.findViewById(R.id.AuctionSpecialInfo_SpecialRL);
        specialRL.setOnClickListener(this);
        specialImg = (DynamicHeightImageView) mHeadView.findViewById(R.id.AuctionSpecialInfo_SpecialImg);
        specialImg.isRightAngle=true;
        title = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_title);
        time = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_PreviewTime);
        address = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_AuctionAddress);
        state = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_state);
        addRemind = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_addRemind);
        addRemind.setOnClickListener(this);
        company_icon = (ImageView) mHeadView.findViewById(R.id.AuctionSpecialInfo_company_icon);
        company_icon.setOnClickListener(this);
        company = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_company);
        num = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_Num);
        downloadCatalogue = (TextView) mHeadView.findViewById(R.id.AuctionSpecialInfo_downloadCatalogue);
        downloadCatalogue.setOnClickListener(this);
        noDataLL = (LinearLayout) findViewById(R.id.ll_hint);
        // 头布局放入listView中
        mListView.addHeaderView(mHeadView);
        mListView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view,
                                    int Position, long id) {
                // TODO Auto-generated method stub
                int position = Position - 2;
                if (position >= 0) {
                    Intent intent = new Intent(mContext, LotDetailPagerActivity.class);
                    intent.putStringArrayListExtra("id", listLotIds);
                    intent.putExtra("index", position);
                    startActivity(intent);
                }
            }

        });
        getSpecialInfoData();
        getLotListData(true);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        // 下拉刷新
        page = 1;
        isRefreshed = true;
        getSpecialInfoData();
        getLotListData(true);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        // 上拉加载
        page++;
        getLotListData(false);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.back_btn:
                // 退出
                finish();
                break;
            case R.id.AuctionInfo_title_collectionBtn:
                // 收藏
                finish();
                break;
            case R.id.tittle_search:
                //分享
                if (mSpecialInfoParser != null) {
                    AppUtil.shareAuction(mContext, "3", mSpecialInfoParser.getTitle(), mSpecialInfoParser.getMemo(), mSpecialInfoParser.getImgurl(),
                            mSpecialInfoParser.getShareurl() + "&type=1", mSpecialInfoParser.getId(), false);
                }
                break;
            case R.id.AuctionSpecialInfo_SpecialRL:
                // 专场信息
                intent = new Intent(mContext, AuctionSpecialInformation_Activity.class);
                intent.putExtra("SpecialID", SpecialID);
                startActivity(intent);
                break;
            case R.id.AuctionSpecialInfo_addRemind:
                // 提醒按钮
                if (mSpecialInfoParser != null) {
                    Intent i2 = new Intent(mContext, AuctionAddRemind_Activity.class);
                    i2.putExtra("SpecialInfoParser", mSpecialInfoParser);
                    startActivity(i2);
                } else {
                    ToastUtil.toast(mContext, "您的信息不完整，请重新加载之后重试");
                }
                break;
            case R.id.AuctionSpecialInfo_downloadCatalogue:
                // 下载图录
                break;
            case R.id.AuctionSpecialInfo_company_icon:
                //机构头像
                intent = new Intent(mContext, AucOrgDetActivity.class);
                intent.putExtra("id", mSpecialInfoParser.getJid());
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    /**
     * 获取专场详情数据
     */
    private void getSpecialInfoData() {
        VolleyBasic.getInstance(this).post(Cache.specialInfo,
                VolleyMap.getInstance().specialInfo(SpecialID,imgwide_SpecialInfo),
                SpecialInfoParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        auctionSpecialInfo_LL.setVisibility(View.VISIBLE);
                        final SpecialInfoParser bean = (SpecialInfoParser) vd.getData();
                        mSpecialInfoParser = bean;
                        specialImg.setHeight(bean.getHeight());
                        Glide.with(mContext).load(bean.getImgurl()).asBitmap().centerCrop().into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                int w = resource.getWidth();
                                int h = resource.getHeight();
                                if(bean.getHeight()==0){
                                    specialImg.setHeight(h);
                                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) company_icon.getLayoutParams();
                                    lp.setMargins(0,(h-150),0,0);
                                    company_icon.setLayoutParams(lp);
                                }else{
                                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) company_icon.getLayoutParams();
                                    lp.setMargins(0,(bean.getHeight()-150),0,0);
                                    company_icon.setLayoutParams(lp);
                                }
                                specialImg.setImageBitmap(resource);
                            }
                        });

                        title.setText(bean.getTitle());
                        int status = bean.getStatus();
                        switch (status) {
                            case 0:
                                // 已结束
                                time.setText(bean.getStart_time() + "-" + bean.getEnd_time());
                                address.setText(bean.getAuction_address());
                                state.setText("已结束");
                                break;
                            case 1:
                                // 待预展
                                time.setText(bean.getStart_time() + "-" + bean.getEnd_time());
                                address.setText(bean.getPreview_address());
                                state.setText("待预展");
                                break;
                            case 2:
                                // 预展中
                                time.setText(bean.getStart_time() + "-" + bean.getEnd_time());
                                address.setText(bean.getPreview_address());
                                state.setText("预展中");
                                break;
                            case 3:
                                // 拍卖中
                                time.setText(bean.getStart_time() + "-" + bean.getEnd_time());
                                address.setText(bean.getAuction_address());
                                state.setText("拍卖中");
                                break;
                            default:
                                break;
                        }
                        Glide.with(mContext).load(bean.getLogo() + "_150x150.png").asBitmap().centerCrop()
                                .placeholder(R.drawable.ic_menu_rotate).error(R.drawable.ic_menu_rotate).into(new MyBitmapImageViewTarget(company_icon));
                        company.setText(bean.getSeller_name());
                        final int is_remind = bean.getIs_remind();
                        switch (is_remind) {
                            case 0:
                                // 0 已经开拍，不能点击
                                addRemind.setVisibility(View.GONE);
                                break;
                            case 1:
                                // 1.添加
                                addRemind.setText("添加提醒");
                                addRemind.setVisibility(View.VISIBLE);
                                break;
                            case 2:
                                // 2. 查看提醒
                                addRemind.setText("查看提醒");
                                addRemind.setVisibility(View.VISIBLE);
                                break;
                            default:
                                break;
                        }
                        if (!TextUtils.isEmpty(bean.getCatalogurl())) {
                            downloadCatalogue.setVisibility(View.VISIBLE);
                        } else {
                            downloadCatalogue.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                    }
                });
    }

    /**
     * 获取拍品列表
     * 加载对话框是否显示
     * 专场id id 页码 page 条数 pagesize 拍品宽度 width 类型 type 默认是1表示专场下的拍品，2认证拍品
     * 用户口令 token 排列顺序 order 当type=2时，排序1.默认 2.成交价
     */
    private void getLotListData(Boolean isLoadDialog) {
        isLoad=false;
        if(isLoadDialog){
            VolleyBasic.showLoding(this);
        }
        VolleyBasic.getInstanceNoDialog(this).post(
                Cache.auction_LotList,
                VolleyMap.getInstance().auction_LotList(page, requestDataNum, SpecialID,
                        "1", imgwide, "1"), AuctionLotListParser.class,
                new VolleyCallback() {
                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        isLoad=true;
                        mListView.setVisibility(View.VISIBLE);
                        auctionSpecialInfo_LL.setVisibility(View.VISIBLE);
                        if(page==1) {
                            try {
                                JSONObject jsonObject = new JSONObject(vd.getJson());
                                dataNum = jsonObject.getInt("num");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (isRefreshed) {
                            mListView.stopRefresh();
                        } else {
                            mListView.stopLoadMore();
                        }
                        AuctionLotListParser bean = (AuctionLotListParser) vd.getData();
                        if (page == 1) {
                            num.setText("备案" + bean.getRecordnum() + "件 / 拍品" + bean.getLotnum() + "件");
                        }
                        list = bean.getLotinfo();
                        if (isRefreshed == true) {
                            more_list.clear();
                            isRefreshed = false;
                        }
                        if (!list.isEmpty()) {
                            more_list.addAll(list);
                        }

                        if (more_list.size() == 0) {
                            mListView.setPullLoadEnable(false);
                        } else {
                            mListView.setPullLoadEnable(true);
                        }
                        listLotIds.clear();
                        for (int i = 0; i < more_list.size(); i++) {
                            String idString = more_list.get(i).getId();
                            listLotIds.add(idString);
                        }
                        if (mAdapter == null) {
                            mAdapter = new AuctionSpecialInfo_Adapter(mContext, more_list);
                            mListView.setAdapter(mAdapter);

                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad=true;
                        if (isRefreshed) {
                            mListView.stopRefresh();
                        } else {
                            mListView.stopLoadMore();
                        }
                    }
                });
    }

    /**
     * 修改系统消息为已读
     */

    private void updataSystmeMessage(final String MessageId) {
        VolleyBasic.getInstance(this).post(Cache.updateSystemread,
                VolleyMap.getInstance().updateSystemread(MessageId),
                UpdataSystemMessageParser.class, new VolleyCallback() {
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        System.out.println(vd.getJson());
                        UpdataSystemMessageParser bean = (UpdataSystemMessageParser) vd.getData();
                        if ("1".equals(bean.getStatus())) {
                            // 成功
                            Log.d("log", "修改推送状态成功：" + MessageId);
                        } else if ("0".equals(bean.getStatus())) {
                            // 失败
                            ToastUtil.toast(mContext, "修改消息状态失败");
                        }
                    }

                    public void onError(VolleyError volleyError) {
                    }
                });
    }

    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getBooleanExtra("addRemind", false)) {
                //判断是否为添加提醒的广播通知
                getSpecialInfoData();
            } else if (intent.getBooleanExtra("Collect", false)) {
                //是否为收藏
                if (intent.getBooleanExtra("isCollect", true)) {
                    //设置为已收藏
                } else {
                    //设置为未收藏
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 关闭广播
        unregisterReceiver(broadcastReceiver);
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("AuctionSpecialInfo_ Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

}
